package com.ls.modules.sys.controller;

import com.ls.base.utils.R;
import com.ls.base.validator.ValidatorUtils;
import com.ls.common.baseClass.BackStageController;
import com.ls.modules.sys.biz.manager.SysCaptchaManager;
import com.ls.modules.sys.biz.manager.SysUserManager;
import com.ls.modules.sys.biz.manager.SysUserTokenManager;
import com.ls.modules.sys.biz.model.LoginModel;
import com.ls.modules.sys.dal.jpa.entity.SysUserEntity;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 登录
 * @author: xiaosu
 * @date: 2018-09-25  17:27
 */
@RestController
public class SysLoginController extends BackStageController {
	@Autowired
	private SysUserManager sysUserManager;
	@Autowired
	private SysUserTokenManager sysUserTokenManager;
	@Autowired
	private SysCaptchaManager sysCaptchaManager;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaManager.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@ApiOperation("登录")
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody LoginModel form)throws IOException {

		ValidatorUtils.validateEntity(form);

		boolean captcha = sysCaptchaManager.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserManager.queryByName(form.getName());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword()))) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenManager.createToken(user.getId());
		return r;
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout() {
		sysUserTokenManager.logout(getUserId());
		return R.ok();
	}
	
}
